package com.hnkywl.sts.util;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;

/**
 * Created by 001 on 2015/11/11.
 */
public class DocumentHandler {
    private Configuration configuration = null;

    public DocumentHandler() {
        configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
    }

    public File  createDoc(Map<String, Object> dataMap) throws UnsupportedEncodingException {
        //dataMap 要填入模本的数据文件
        //设置模本装置方法和路径,FreeMarker支持多种模板装载方法。可以重servlet，classpath，数据库装载，
        //这里我们的模板是放在template包下面
        configuration.setClassForTemplateLoading(this.getClass(), "/com/hnkywl/sts/template");
        Template t = null;
        try {
            //test.ftl为要装载的模板
            t = configuration.getTemplate("template.ftl");
        } catch (IOException e) {
            e.printStackTrace();
        }
        String name = "temp" + (int) (Math.random() * 100000) + ".doc";
        File f = new File(name);
        Writer out;
        try {
            out = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
            t.process(dataMap, out);
            out.close();
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return f;
    }
}
